<template>
  <div class="add" v-loading="loading">
    <div class="forbid-height" v-if="pageShow == true" @click="forbidHit"></div>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="城市名称" prop="name">
        <div class="parallel">
          <el-input style="width: 300px" v-model="ruleForm.name" placeholder="请输入模板名称" clearable></el-input>
        </div>
      </el-form-item>

      <el-form-item label="是否包邮" prop="radio">
        <div class="parallel">
          <el-radio v-model="ruleForm.radio" v-for="(item, index) in 2" :key="index" :label="index">{{ index == 0 ?
            "自定义运费" : "包邮" }}</el-radio>
        </div>
      </el-form-item>

      <el-form-item label="计价模式" prop="valuation">
        <div class="parallel">
          <el-radio v-model="ruleForm.valuation" v-for="(item, index) in 2" :key="index" :label="index">{{ index == 0 ?
            "按件数" : "按重量" }}</el-radio>
        </div>
      </el-form-item>

      <el-form-item label="运送方式" class="from-ship" v-if="ruleForm.radio == 0">
        <div class="ship">
          <div class="top">除指定地区外，其余地区的运费采用 “ 默认运费 ”</div>

          <div class="center">
            <div class="left">
              默认运费
              <el-input style="width: 200px; margin: 0 10px" v-model="ruleForm.defaultFreightWeight"
                placeholder="请输入默认运费重量" clearable></el-input>
              {{ ruleForm.valuation == 0 ? "件" : "kg" }}内
              <el-input style="width: 200px; margin: 0 10px" v-model="ruleForm.defaultFreightPrice"
                placeholder="请输入默认运费" clearable></el-input>
              元
            </div>
            <div class="right">
              每增加
              <el-input style="width: 100px; margin: 0 10px" v-model="ruleForm.addFreightWeight" placeholder="请输入默认运费重量"
                clearable></el-input>
              {{ ruleForm.valuation == 0 ? "件" : "kg" }}内， 增加运费
              <el-input style="width: 100px; margin: 0 10px" v-model="ruleForm.addFreightPrice" placeholder="请输入默认运费"
                clearable></el-input>
              元
            </div>
          </div>

          <div class="text" @click="freightHit">为指定地区城市设置运费</div>

          <div class="table" v-if="addressListOpt.length > 0">
            <el-table v-loading="loading" :data="addressListOpt" border :header-cell-style="{
              color: '#333333',
              backgroundColor: '#f3f3f3',
            }">
              <el-table-column prop="" label="运送到省">
                <template slot-scope="scope">
                  {{ scope.row.provinceName }}
                </template>
              </el-table-column>

              <el-table-column prop="" label="运送到市" width="300">
                <template slot-scope="scope">
                  <el-tag class="wrap-tag">
                    {{ scope.row.cityNameList }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="" label="首重量（kg）">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.startUnit" placeholder="请输入首重量（kg）" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="" label="首费（元）">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.startPrice" placeholder="请输入首费（元）" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="" label="续重量（kg）">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.addUnit" placeholder="请输入续重量（kg）" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="" label="续费（元）">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.addPrice" placeholder="请输入续费（元）" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="" label="操作">
                <template slot-scope="scope">
                  <div class="operation">
                    <div class="list" @click.prevent="editHit(scope.row)">
                      编辑
                    </div>
                    <div class="list" @click.prevent="deleteHit(scope.row)">
                      删除
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form-item>

      <el-form-item class="mission" v-if="pageShow == false">
        <div class="form-button">
          <div class="list" @click="addClose">取消</div>
          <div class="list" @click="addConfirm('ruleForm')">保存</div>
        </div>
      </el-form-item>
    </el-form>

    <div class="address">
      <el-dialog title="选择区域" :visible.sync="freightVisible" :before-close="freightClose">
        <div class="address-popup">
          <div class="popup-center">
            <div class="list" v-for="(item, index) in cities" :key="index">
              <div class="list-first">
                <el-checkbox :ref="'checkbox' + index" v-model="item.checkAll" :indeterminate="item.isIndeterminate"
                  @change="handleCheckAllChange(index)">{{ item.text }}</el-checkbox>
              </div>

              <div class="list-parallel">
                <el-checkbox-group :ref="'roup' + index" v-model="item.checkedCities"
                  @change="handleCheckedCitiesChange">
                  <div class="array" v-for="(info, num) in item.data" :key="num" @click.stop="groupClick(index)">
                    <el-checkbox v-model="info.checkAll" :label="info.text" :key="info.id">{{ info.text }}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </div>

            <!-- <el-tree
              ref="tree"
              :data="addressList"
              :props="defaultProps"
              show-checkbox
              node-key="id"
            ></el-tree> -->
          </div>

          <div class="popup-button">
            <div class="button" v-for="(item, index) in 2" :key="index" @click="buttonHit(index)">
              {{ index == 0 ? "保存" : "取消" }}
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { commonDistrictList } from "@/api/common";

import { uniqueArrayOfObjects } from "@/utils/deWeight";

import { savePostagegoodListId, savePostagegoodListIdAdd } from "@/api/save";

var throttle = require("@/utils/throttle"); // 防抖

export default {
  data() {
    return {
      id: "",
      pageShow: false, // 是否可修改
      ruleForm: {
        name: "",
        radio: "",
        valuation: "",
        //---------------------
        defaultFreightWeight: "",
        defaultFreightPrice: "",
        addFreightWeight: "",
        addFreightPrice: "",
      },
      rules: {
        name: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
        radio: [
          { required: true, message: "请选择是否包邮", trigger: "change" },
        ],
        valuation: [
          { required: true, message: "请选择计价模式", trigger: "change" },
        ],
      },
      //-------
      page: 1,
      limit: 10,
      tableData: [],
      tableDataTotal: 0,
      loading: false,
      //-------------
      freightVisible: false,
      freightObj: {},
      //--------------------
      addressList: [],
      defaultProps: {
        // children: "data",
        label: "text",
      },
      addressListOpt: [],

      //------------------------
      checkedCities: [],
      cities: [],
      citiesIndex: null,
    };
  },
  created() {
    this.pageShow = this.$route.query.soucre == 10 ? true : false;

    if (this.$route.query.id) {
      this.loading = true;

      this.id = this.$route.query.id;
      this.savePostagegoodListIdMet();
    }

    this.commonDistrictListMet();
  },
  methods: {
    //----------------------
    forbidHit() {
      this.$message.error("当前详情页，禁止修改");
    },
    commonDistrictListMet() {
      let params = {};

      commonDistrictList(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.forEach((item, index) => {
            item.checkAll = false;
            item.checkedCities = [];
            item.have = false;
            item.isIndeterminate = true;
            item.cityList = [];

            item.data.forEach((info, num) => {
              info.checkAll = false;
            });
          });
          // this.addressList = res.resultData;
          this.cities = res.resultData;
        }
      });
    },
    //-----------------------------
    savePostagegoodListIdMet() {
      let params = this.id;
      savePostagegoodListId(params).then((res) => {
        if (res.errorCode == null) {
          this.freightObj = res.resultData;
          //--------------------------
          this.ruleForm.name = res.resultData.goodPostageName;
          this.ruleForm.radio = res.resultData.isFree;
          this.ruleForm.valuation = res.resultData.billingType;
          //---------------------------
          this.ruleForm.defaultFreightWeight = res.resultData.startUnit;
          this.ruleForm.defaultFreightPrice = Number(
            res.resultData.startPrice / 100
          );
          this.ruleForm.addFreightWeight = res.resultData.addUnit;
          this.ruleForm.addFreightPrice = Number(res.resultData.addPrice / 100);
          //-------------------------------
          if (res.resultData.goodPostageShowList.length > 0) {
            res.resultData.goodPostageShowList.forEach((item, index) => {
              item.startUnit = Number(item.startUnit);
              item.startPrice = Number(item.startPrice / 100);
              item.addUnit = Number(item.addUnit);
              item.addPrice = Number(item.addPrice / 100);
              item.provinceName = item.regionNameList;
              item.provinceList = item.regionIdList;
              item.cityNameList = item.cityNameList
              //     citiesId = item.regionIdList;
            });
          }

          this.addressListOpt = res.resultData.goodPostageShowList;

          this.loading = false;
        }
      });
    },

    //------------------------
    handleCheckAllChange(num) {
      this.cities.forEach((item, index) => {
        if (num == index) {
          if (item.checkAll == true) {
            item.checkAll = true;
            item.have = true;
            item.isIndeterminate = false;

            item.data.forEach((v, j) => {
              v.checkAll = true;
              item.checkedCities.push(v.text);
            });
          } else {
            item.checkAll = false;
            item.have = false;
            item.isIndeterminate = true;

            item.data.forEach((v, j) => {
              v.checkAll = false;
              item.checkedCities = [];
            });
          }
        }
      });
      this.isIndeterminate = false;
    },
    groupClick(index) {
      this.citiesIndex = index;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;

      this.$nextTick(() => {
        let checkAll =
          checkedCount === this.cities[this.citiesIndex].data.length;
        if (checkAll == true) {
          this.cities.forEach((item, index) => {
            if (this.citiesIndex == index) {
              item.checkAll = true;
              item.isIndeterminate = false;
              item.have = true;
            }
          });
        } else {
          this.cities.forEach((item, index) => {
            if (this.citiesIndex == index) {
              item.checkAll = false;

              item.isIndeterminate = true;

              item.data.forEach((v, j) => {
                value.forEach((info, num) => {
                  if (v.text == info) {
                    item.have = true;
                  }
                });
              });

              // 数组对象（A）
              const arrValues = value;

              // 直接修改原数组
              item.data.forEach((info) => {
                if (arrValues.includes(info.text)) {
                  info.checkAll = true;
                } else {
                  info.checkAll = false;
                }
              });
            }
          });
        }
      });
    },
    freightClose() {
      this.freightVisible = false;
    },

    deleteHit(index) {
      this.addressListOpt.splice(index, 1);
    },
    freightHit() {
      if (this.$route.query.id) {
        this.addHit(this.freightObj.goodPostageShowList[0]);
      }
      this.freightVisible = true;
    },
    buttonHit(index) {
      if (index == 0) {
        const province = this.cities.filter((info) => info.have === true);

        let provinceList = [];

        let cityList = []

        province.forEach((item, index) => {
          provinceList.push(item.text);
          item.cityList = item.data.filter((info) => info.checkAll === true);
          cityList.push(item)
        });

        let provinceName = provinceList.join(";");

        //-----------------
        let citySecondList = []

        cityList.forEach((item, index) => {
          citySecondList.push(...item.cityList)
        })

        let cityThree = []

        citySecondList.forEach((item, index) => {
          cityThree.push(item.text)
        })
        let cityNameList = cityThree.join(";");
        console.log('获取市级名称', cityNameList)
        //-------


        let firstObj = {
          provinceName: provinceName,
          provinceList: province,
          cityNameList: cityNameList
        };

        if (provinceList.length > 0) {
          this.addressListOpt = [];
          this.addressListOpt.push(firstObj);
        }


        this.freightVisible = false;
      } else {
        this.freightVisible = false;
      }
    },
    //-----------
    addClose() {
      this.$router.push({
        path: "/save/operation/operation-freight",
      });
    },
    addConfirm: throttle.throttle(function (formName) {
      const list = JSON.parse(JSON.stringify(this.addressListOpt));
      const id = [];

      list.forEach((item, index) => {
        item.provinceList.forEach((ele) => {
          if (ele.id) {
            id.push(ele.id);

            if (ele.cityList.length > 0) {
              ele.cityList.forEach((key) => {
                id.push(key.id);
              });
            }
          } else {
            id.push(ele)
          }
        });
      });

      list.forEach((item) => {
        item.startUnit = Number(item.startUnit);
        item.startPrice = Number(item.startPrice * 100);
        item.addUnit = Number(item.addUnit);
        item.addPrice = Number(item.addPrice * 100);
        item.regionIdList = id;
        item.regionNameList = item.provinceName;
      });

      list.map((item) => {
        delete item.provinceList; // 直接删除对象的 provinceName 键
        delete item.provinceName; // 直接删除对象的 provinceName 键
        return item;
      });

      console.log("获取list", list);

      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {};

          if (this.ruleForm.radio == 0) {
            params = {
              goodPostageId: this.id,
              goodPostageName: this.ruleForm.name,
              isFree: this.ruleForm.radio,

              //-----------------
              billingType: this.ruleForm.valuation,

              startUnit: Number(this.ruleForm.defaultFreightWeight),
              startPrice: Number(this.ruleForm.defaultFreightPrice * 100),

              addUnit: Number(this.ruleForm.addFreightWeight),
              addPrice: Number(this.ruleForm.addFreightPrice * 100),
              goodPostageShowList: list,
            };
          } else {
            params = {
              goodPostageId: this.id,
              goodPostageName: this.ruleForm.name,
              isFree: this.ruleForm.radio,
              //-----------------
              billingType: this.ruleForm.valuation,
            };
          }

          savePostagegoodListIdAdd(params).then((res) => {
            if (res.errorCode == null) {
              if (this.id == "") {
                this.$message.success("新增运费模板成功！");
              } else {
                this.$message.success("编辑运费模板成功！");
              }

              setTimeout(() => {
                this.$router.push({
                  path: "/save/operation/operation-freight",
                });
              }, 1000);
            }
          });
        } else {
          return false;
        }
      });
    },  3000),
    //--
    addHit(item) {
      console.log("点击编辑", item);
      // return
      // 数组对象（A）
      const arrValues = item.provinceList;

      // 直接修改原数组
      this.cities.forEach((info, index) => {
        if (arrValues.includes(info.id)) {
          info.have = true;
          if (info.id == 2 || info.id == 1) {
            info.checkAll = true;
            this.handleCheckAllChange(index);
          }

          info.data.forEach((obj) => {
            if (arrValues.includes(obj.id)) {
              info.checkedCities.push(obj.text);
              info.cityList.push(obj);
              obj.checkAll = true;
            } else {
              obj.checkAll = false;
            }
          });
        } else {
        }
      });

      this.cities = this.cities;

      // this.commonDistrictListMet();

      this.$nextTick(() => {
        this.freightVisible = true;
      });
    },
    editHit(item) {
      console.log("点击编辑", item);
      // return
      // 数组对象（A）
      const arrValues = item.provinceList;

      // 直接修改原数组
      this.cities.forEach((info, index) => {
        if (arrValues.includes(info.id)) {
          info.have = true;
          if (info.id == 2 || info.id == 1) {
            info.checkAll = true;
            this.handleCheckAllChange(index);
          }

          info.data.forEach((obj) => {
            if (arrValues.includes(obj.id)) {
              info.checkedCities.push(obj.text);
              info.cityList.push(obj);
              obj.checkAll = true;
            } else {
              obj.checkAll = false;
            }
          });
        } else {
        }
      });

      this.cities = this.cities;

      this.$nextTick(() => {
        this.freightVisible = true;
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import url("@/assets/css/delete.less");
@import url("@/assets/css/common.less");

.add {

  .forbid-height {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 10;
    display: flex;
  }


  .demo-ruleForm {
    .from-ship {
      width: 80%;

      /deep/ .el-form-item__content {
        margin-left: 0 !important;
      }

      .ship {
        .top {
          color: #dc5555;
          font-family: PingFangSC, PingFang SC;
          font-weight: bold;
          margin-left: 20px;
        }

        .center {
          margin-left: 110px;
          padding: 4px 10px;
          box-sizing: border-box;
          margin-top: 10px;
          border: 1px solid #ccc;
          border-radius: 4px;
          display: flex;
          align-items: center;

          .left,
          .right {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            color: #666666;
          }

          .right {
            margin-left: 100px;
          }
        }

        .text {
          margin-left: 120px;
          font-family: PingFangSC, PingFang SC;
          font-weight: bold;
          color: #2878ff;
          cursor: pointer;
        }

        .table {
          margin-left: 120px;
          margin-top: 20px;



          /* 基础换行样式 */
          .wrap-tag {
            /* 允许换行 */
            white-space: normal !important;
            /* 让标签能够适应内容高度 */
            height: auto;
          }
        }
      }
    }

    .form-button {
      display: flex;
      align-items: center;
      margin-top: 100px;

      /deep/ .el-form-item__content {
        line-height: 0;
      }

      /deep/ .el-form-item__content {
        margin-left: 120px !important;
      }

      .list {
        background: #3da8f5;
        color: #fff;
        font-size: 16px;
        margin-right: 20px;
        border-radius: 5px;
        width: 80px;
        height: 35px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }

      .list:first-child {
        z-index: 11;
        position: relative;
      }

      .list:first-child {
        background: #808080;
      }
    }
  }

  .address {
    /deep/ .el-dialog__header {
      font-size: 16px;
      font-weight: bold;
      text-align: left;
    }

    /deep/ .el-dialog__body {
      padding-bottom: 10px;
    }

    .address-popup {
      .popup-center {
        height: 400px;
        overflow: auto;

        .list {
          .list-first {
            display: flex;
            align-items: center;
            height: 35px;
          }

          .list-parallel {
            display: flex;
            flex-wrap: wrap;
            padding: 0 10px;
            box-sizing: border-box;

            /deep/ .el-checkbox-group {
              width: 100%;
              display: flex;
              flex-wrap: wrap;
            }

            .array {
              width: calc((100% / 5));
              height: 35px;
              display: flex;
              align-items: center;
            }
          }
        }
      }

      .popup-button {
        border-top: 1px solid #ccc;
        padding: 10px 0;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .button {
          padding: 9px 20px;
          box-sizing: border-box;
          border-radius: 5px;
          background: #2a82e4;
          font-size: 14px;
          color: #fff;
          margin-left: 20px;
          cursor: pointer;
        }

        .button:last-child {
          background: #999999;
        }
      }
    }
  }
}
</style>